import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import json
import sys

# 加载两个JSON文件
def load_cell_points(file_path):
    with open(file_path) as f:
        data = json.load(f)
    return [
        cell.get('bbox', {}) 
        for cell in data.get('cells', []) 
        if isinstance(cell.get('bbox'), dict)
    ]

# 解析命令行参数
import os
# 转换绝对路径
import os
# 增强路径验证
if not os.path.exists(sys.argv[1]) or not os.path.exists(sys.argv[2]):
    print("错误：输入文件不存在")
    sys.exit(1)

file1 = os.path.abspath(sys.argv[1])
file2 = os.path.abspath(sys.argv[2])
print(f'正在处理:\n源文件: {file1}\n对比文件: {file2}\n工作目录: {os.getcwd()}')

# 获取第一个单元格坐标
points1 = load_cell_points(file1)[0]
# 加载坐标点并验证
try:
    points1 = load_cell_points(file1)
    points2 = load_cell_points(file2)
    
    if not points1 or not points2:
        raise ValueError("空坐标数据")
    
    # 取第一个有效单元格
    cell1 = next((cell for cell in points1 if cell), None)
    cell2 = next((cell for cell in points2 if cell), None)
    
    if not cell1 or not cell2:
        raise ValueError("未找到有效单元格坐标")

except Exception as e:
    print(f"加载失败: {str(e)}")
    sys.exit(1)


# 创建画布
plt.figure(figsize=(14, 8))

# 创建对比子图
ax1 = plt.subplot(121)
ax2 = plt.subplot(122)

# 定义绘图函数
def plot_quad(ax, points, title):
    ordered_keys = ['p1','p2','p3','p4']
    valid_points = {k:v for k,v in points.items() if k in ordered_keys}
    ordered_points = [valid_points.get(key, [0,0]) for key in ordered_keys]
    
    # 绘制连接顺序
    for i in range(4):
        start = ordered_points[i]
        end = ordered_points[(i+1)%4]
        ax.plot([start[0], end[0]], [start[1], end[1]], 
                linestyle='--' if i%2 else '-',
                linewidth=2,
                label=f'p{i+1}-p{(i+1)%4+1}')
    
    # 标注点顺序
    for idx, (key, coord) in enumerate(points.items()):
        ax.scatter(coord[0], coord[1], s=100, zorder=5)
        ax.text(coord[0]+2, coord[1]+2, f'{key}({idx+1})', 
                fontweight='bold', fontsize=10,
                bbox=dict(facecolor='yellow', alpha=0.7))
    
    ax.set_title(title)
    ax.grid(True)
    ax.axis('equal')
    ax.legend()

# 绘制对比
plot_quad(ax1, points1, '合格文件坐标顺序')
plot_quad(ax2, points2, '待校准文件坐标顺序')  # 连接顺序
x_coords = [points[p][0] for p in ordered_points]
y_coords = [points[p][1] for p in ordered_points]
plt.plot(x_coords, y_coords, 'b-', linewidth=2)

# 绘制点并添加标签
for name, coord in points.items():
    plt.scatter(coord[0], coord[1], color='red', s=100, zorder=5)
    plt.text(coord[0]+1, coord[1]+1, name, 
             fontsize=12, 
             fontweight='bold',
             bbox=dict(facecolor='white', alpha=0.8, edgecolor='none'))

# 设置图形属性
plt.title('四边形可视化', fontsize=14, pad=20)
plt.xlabel('X 坐标', fontsize=12)
plt.ylabel('Y 坐标', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.axis('equal')

# 自动调整坐标轴范围
margin = 5
plt.xlim(min(x_coords)-margin, max(x_coords)+margin)
plt.ylim(min(y_coords)-margin, max(y_coords)+margin)

# 显示图形
plt.tight_layout()
import os
output_dir = os.path.dirname(file1)
output_path = os.path.join(output_dir, 'comparison_result.png')
try:
    plt.savefig(output_path, dpi=300, bbox_inches='tight')
    print(f'对比图已保存至: {output_path}')
print('\n运行状态报告：')
print(f'1. 源文件单元格数: {len(points1)} | 对比文件单元格数: {len(points2)}')
print(f'2. 输出文件尺寸: {os.path.getsize(output_path)} bytes')
print(f'3. 运行成功！请检查对比图: {output_path}')
except Exception as e:
    print(f'保存失败: {str(e)}')
    plt.close('all')
    sys.exit(1)
plt.close('all')